import logging

from sqlalchemy import select
from sqlalchemy.exc import DBAPIError, IntegrityError

from src.core.exceptions.common import RepoError
from src.core.exceptions.user import (
    UserIdAlreadyExist,
    UserIdNotExist,
    UserTgIdAlreadyExist,
    UserTgIdNotExist,
)
from src.core.models.dto import UserDTO
from src.database.converters.user import convert_db_model_to_user_dto
from src.database.exception_mapper import exception_mapper
from src.database.models import User
from src.database.repositories.base import SQLAlchemyRepo

logger = logging.getLogger(__name__)


class UserReaderImpl(SQLAlchemyRepo):
    @exception_mapper
    async def get_user_by_id(self, user_id: int) -> UserDTO:
        """Получаем пользователя по id"""

        user: User | None = await self._session.scalar(
            select(User).where(
                User.id == user_id,
            )
        )
        if not user:
            raise UserIdNotExist

        return convert_db_model_to_user_dto(user)

    @exception_mapper
    async def get_user_by_tg_id(self, user_tg_id: int) -> UserDTO:
        """Получаем пользователя по telegram id"""

        user: User | None = await self._session.scalar(
            select(User).where(
                User.telegram_id == user_tg_id,
            )
        )
        if not user:
            raise UserTgIdNotExist

        return convert_db_model_to_user_dto(user)

    @exception_mapper
    async def get_users(self) -> list[UserDTO]:
        """Получаем пользователей"""

        res = await self._session.scalars(select(User))
        users: list[User] = list(res)

        return [convert_db_model_to_user_dto(user) for user in users]


class UserRepoImpl(SQLAlchemyRepo):
    @exception_mapper
    async def acquire_user_by_id(self, user_id: int) -> User:
        """Получаем пользователя по id"""

        user: User | None = await self._session.scalar(
            select(User)
            .where(
                User.id == user_id,
            )
            .with_for_update()
        )
        if not user:
            raise UserIdNotExist

        return user

    @exception_mapper
    async def acquire_user_by_tg_id(self, user_tg_id: int) -> User:
        """Получаем пользователя по telegram id"""

        user: User | None = await self._session.scalar(
            select(User).where(
                User.telegram_id == user_tg_id,
            )
        )
        if not user:
            raise UserTgIdNotExist

        return user

    @exception_mapper
    async def create_user(self, user: User) -> None:
        """Создаем пользователя"""

        self._session.add(user)
        try:
            await self._session.flush((user,))
        except IntegrityError as err:
            self._parse_error(err)

    @exception_mapper
    async def update_user(self, user: User) -> None:
        """Обновляем пользователя"""

        try:
            await self._session.merge(user)
        except IntegrityError as err:
            self._parse_error(err)

    @staticmethod
    def _parse_error(err: DBAPIError) -> None:
        """Определение ошибки"""

        error_msg = err.__cause__.args[1]

        if "pk_user" in error_msg:
            raise UserIdAlreadyExist from err
        elif "uq_user_telegram_id" in error_msg:
            raise UserTgIdAlreadyExist from err
        else:
            raise RepoError from err
